﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_2._2.Models;
using Project_2._2.ViewModels;
using System.IO;
using Project_2._2.Extra;
using System.Web.Security;
using PagedList;
using PagedList.Mvc;
using System.Data.Entity.Validation;
using System.Diagnostics;


namespace Project_2._2.Controllers
{
    public class AdminNewsController : Controller
    {
        //
        // GET: /TinTuc/

        private QuanLyThueXeEntities db = new QuanLyThueXeEntities();
        private Common cm = new Common();
        public ActionResult Default(int? page, string rd, string Record)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    if (rd != null)
                    {
                        int record = int.Parse(rd);
                        var tt = (from p in db.TinTucs where p.isDelete == false select p).ToList().ToPagedList(page ?? 1, record);
                        ViewBag.record = rd;
                        return View(tt);
                    }
                    else
                    {

                        var tt = (from p in db.TinTucs where p.isDelete == false select p).ToList().ToPagedList(page ?? 1, 3);
                        return View(tt);
                    }
                }
                else
                    return RedirectToAction("Login", "Admin");
            }
        }
        [HttpPost]
        public ActionResult Default(FormCollection col, int? page)
        {
            int record = 0;
            if (string.IsNullOrEmpty(col["KeyWord"]))
            {
                record = int.Parse(col["Record"]);
                var tt = (from p in db.TinTucs where p.isDelete == false select p).ToList().ToPagedList(page ?? 1, record);
                ViewBag.record = col["Record"];
                return View(tt);
            }
            else
            {
                string SearchBy = col["SearchBy"].ToString();
                string key = col["KeyWord"].ToString();

                switch (SearchBy)
                {
                    case "TieuDe":
                        var tt = (from p in db.TinTucs where p.isDelete == false & p.TieuDe.Contains(key) select p).ToList().ToPagedList(page ?? 1, 1);
                        ViewBag.record = "1";
                        return View(tt); break;
                }
                return View();
            }
        }

        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput (false)]
        public ActionResult Create(TinTuc_ViewModels tt, HttpPostedFileBase uploadFile)
        {
                if (ModelState.IsValid)
                {
                     try
                        {
                    TinTuc tintuc = new TinTuc();
                    var mad = (from p in db.People select p.PersonId).First();
                    Session["mad"] = mad;
                    tintuc.PersonId = int.Parse(Session["mad"].ToString());
                    tintuc.TieuDe = tt.TieuDe;
                    if (uploadFile != null && uploadFile.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(uploadFile.FileName);
                        var path = Path.Combine(Server.MapPath("~/Images/AnhDaiDien/"), fileName); uploadFile.SaveAs(path);
                        tintuc.HinhDaiDien = fileName;
                    }
                    tintuc.NoiDung = tt.NoiDung;
                    tintuc.NgayDang = DateTime.Now.Date;
                    tintuc.isDelete = false;
                    tintuc.TomTat = tt.TomTat;
                    db.TinTucs.Add(tintuc);
                    db.SaveChanges();
                    ModelState.Clear();
                    tt = new TinTuc_ViewModels();
                    ModelState.AddModelError("", "Đã thêm thành công...!");
                     }
                     //catch (DbEntityValidationException dbEx)
                    catch
                     {
                         //var errorList = new List<string>();

                         //foreach (var validationErrors in dbEx.EntityValidationErrors)
                         //{
                         //    foreach (var validationError in validationErrors.ValidationErrors)
                         //    {
                         //        errorList.Add(String.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage));
                         //    }
                         //}
                         //return Json(errorList);
                        return RedirectToAction("Default","AdminNews");
                     }
 
                }
                return View(tt);
        }

        public ActionResult Update(int id)
        {
            var tt = (from p in db.TinTucs where p.TinTucId == id select p).First();
            return View(tt);
        }
        [HttpPost]
        public ActionResult Update(int id, FormCollection col, HttpPostedFileBase uploadFile)
        {
            try
            {
                var tt = (from p in db.TinTucs where p.TinTucId == id select p).First();
                var mad = (from p in db.People select p.PersonId).First();
                Session["mad"] = mad;
                tt.PersonId = int.Parse(Session["mad"].ToString());
                tt.TieuDe = col["TieuDe"];
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/AnhDaiDien/"), fileName); uploadFile.SaveAs(path);
                    tt.HinhDaiDien = fileName;
                }
                tt.NgayDang = DateTime.Parse(col["NgayDang"]);
                tt.TomTat = col["TomTat"];
                tt.NoiDung = col["NoiDung"];
                UpdateModel(tt);
                db.SaveChanges();
                ModelState.AddModelError("", "Cập nhật thành công.");
                return RedirectToAction("Default");
            }
            catch (DbEntityValidationException dbEx)
            {
                var errorList = new List<string>();

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errorList.Add(String.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
                return Json(errorList);
            }
           
        }
        public ActionResult Delete(int id)
        {
            try
            {
                TinTuc tt = (from p in db.TinTucs where p.TinTucId == id select p).First();
                tt.isDelete = true;
                UpdateModel(tt);
                db.SaveChanges();
                return RedirectToAction("Default", "AdminNews");
            }
            catch
            {
                return RedirectToAction("Default", "AdminNews");
            }

        }
        [HttpPost]
        public ActionResult Multi_Delete(IEnumerable<int> multi_delete_tintuc)
        {
            try
            {
                var tt_delete = db.TinTucs.Where(x => multi_delete_tintuc.Contains(x.TinTucId)).ToList();
                foreach (var dv in tt_delete)
                {
                    dv.isDelete = true;
                    UpdateModel(dv);
                    db.SaveChanges();
                }
                return RedirectToAction("Default", "AdminNews");
            }
            catch
            {
                return RedirectToAction("Default", "AdminBrandOfCar");
            }

        }
    }
}
